//
//  Mapper.swift
//  native_dio_adapter
//
//  Created by Doris on 2023/3/29.
//
import Alamofire

struct NativeRequestOptions {
    var url: String = ""
    var method: HTTPMethod = .connect
    var headers: HTTPHeaders?
    var parameters: Parameters?
    var timeout: Int = 5
    var encoding: ParameterEncoding =  URLEncoding.default
    
    func getEncoding(isArrayParam:Bool) -> ParameterEncoding {
        let encoding = URLEncoding(arrayEncoding: .noBrackets, boolEncoding: .literal)
        switch method {
        case .get, .head:
            return encoding
        default:
            
            let contentType = headers?.value(for: "Content-Type")
            let isJson = contentType?.contains("application/json") ?? false
            if(isJson)
            {
                return isArrayParam ? ArrayEncoding() : JSONEncoding.default
            }

          }
        return encoding
    }
    
    
    static func fromMap(_ map:[String: Any?]) -> NativeRequestOptions{
        var option = NativeRequestOptions()
        option.url = map["url"] as? String ?? ""
        let method = map["method"] as? String ?? ""
        option.method = HTTPMethod(rawValue: method)
        let header = map["headers"] as? [String: String] ?? [String: String]()
        option.headers = HTTPHeaders(header)
        let param = map["parameters"]
        var isArrayParam = false;
        if(param is Array<Any>){
            option.parameters = (param as! Array<Any>).asParameters()
            isArrayParam = true
        } else{
            option.parameters  = param as? Parameters
        }
        option.encoding = option.getEncoding(isArrayParam: isArrayParam)
        option.timeout = map["timeOut"] as? Int ?? 5
        return option
    }
}

struct NativeMultipartFile {
    var key: String
    var value: [DioFileOptions] =  [DioFileOptions]()
    
    static func fromMap(_ map:[String: Array<[String:String]>]) -> [NativeMultipartFile]{
        var result = [NativeMultipartFile]()
        for (key,content) in map{
            var obj = NativeMultipartFile(key: key)
            var files = [DioFileOptions]()
            for item in content {
                let file = DioFileOptions.fromMap(item)
                if(file == nil){
                    break
                }
                files.append(file!)
            }
            obj.value = files
            result.append(obj)
        }
        return result
    }
}

struct DioFileOptions{
    var data: Data
    var fileName: String?
    var mediaType: String?

    static func fromMap(_ map:[String:String]) -> DioFileOptions?{
        let filePath = map["filePath"] ?? ""
        let fileManager = FileManager.default
        //let exist = fileManager.fileExists(atPath: filePath)
        let data = fileManager.contents(atPath: filePath)
        if(data == nil) {
            return nil
        }
        let option = DioFileOptions(data: data!, fileName:  map["fileName"] , mediaType:  map["mediaType"] )
        return option
    }

}

//------------------------------- ^_^ 结果 ^_^ ---------------------------------
//----------------------------------------------------------------------------

struct AFRequestResult{
    var response: NativeResponse?
    var failure: String?
    
    
    init(response: NativeResponse?,failure: String? = nil) {
        self.response = response
        if(failure != nil){
            self.failure = "SwiftNativeDioAdapterPlugin: \(failure!)"
        }
        
    }
    func toMap() -> [String: Any?] {
        return [
            "response":response?.toMap(),
            "failure": failure,
        ]
    }
}

struct NativeResponse {
    var data: Any?
    var headers: [String: String]?
    var statusCode: Int?
    var statusMessage: String?
    
    init(data: Any?) {
        self.data = data
    }
    
    func toMap() -> [String: Any?] {
        return [
            "data":data,
            "headers": headers,
            "statusCode":statusCode,
            "statusMessage":statusMessage]
    }
}
